// miniprogram/pages/applications/getticket/getticket.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let id = options.id;
    this.getTicketDetail(id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  receiveTicket() {
    let _this = this;
    let db = wx.cloud.database();
    let tinfo = this.data.tinfo;
    let _ = db.command;
    let datas={};
    for (let i in tinfo) {
        if(i!="_openid"){
          if(i=='_id'){
            datas.ticket_id=tinfo[i];
          }else{
            datas[i] = tinfo[i];
          }
        }
    }
    datas.ticket_status='1';
    wx.cloud.callFunction({
      name: 'login',
      success: res => {
        let openid = res.result.openid;
        db.collection('tb_user_list').where({
          _openid: openid
        }).get({
          success: res => {
            console.log(res.data[0]);
            let tickets=res.data[0].user_tickets;
            if(tickets.length>0){
              console.log(tickets)
              console.log(datas.ticket_id)
              for (let i = 0; i < tickets.length; i++) {
                if (tickets[i].ticket_id == datas.ticket_id){
                  return wx.showToast({
                    title: '已领取该优惠券',
                  })
                }
            }
            }
            console.log(tickets);
            db.collection('tb_user_list').doc(res.data[0]._id).update({
                 data:{
                   user_tickets: _.push(datas)
                 },
                 success:resp=>{
                   console.log(resp)
                   wx.showToast({
                     title: '领取成功',
                   })
                 },
                 fail:errp=>{
                    console.log(errp)
                   wx.showToast({
                     title: '领取失败',
                   })
                 }
            })
          },
          fail: err => {
            console.log(err)
          }
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },
  getTicketDetail(id) {
    let _this = this;
    let db = wx.cloud.database();
    db.collection('tb_ticket_list').doc(id).get({
      success: res => {
        console.log(res);
        _this.setData({
          tinfo: res.data
        })
      },
      fail: err => {
        console.log(err);
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})